package server.startup;

import server.*;
import server.core.StandardContext;

import java.io.File;

public class HostConfig implements LifecycleListener {
    private Host host = null;

    protected void log(String message) {
        Logger logger = null;
        if (host != null)
            logger = host.getLogger();
        if (logger != null)
            logger.log("HostConfig[" + host.getName() + "]: " + message);
        else
            System.out.println("HostConfig[" + host.getName() + "]: " + message);
    }

    private void log(String message, Throwable throwable) {
        Logger logger = null;
        if (host != null)
            logger = host.getLogger();
        if (logger != null)
            logger.log("HostConfig[" + host.getName() + "] " + message, throwable);
        else {
            System.out.println("HostConfig[" + host.getName() + "]: " + message);
            throwable.printStackTrace(System.out);
        }
    }

    @Override
    public void lifecycleEvent(LifecycleEvent event) {
        try {
            host = (Host)event.getLifecycle();
        } catch (Throwable t) {
            return;
        }
        if (Lifecycle.START_EVENT.equals(event.getType())) {
            configContext();
        }
    }

    private void configContext() {
        String webPath = System.getProperty("user.dir") + File.separator + "webapps";
        File file = new File(webPath);
        if (!file.exists() || !file.isDirectory())
            return;

        File[] contextDirs = file.listFiles();
        if (contextDirs == null)
            return;

        for (File contextDir : contextDirs) {
            if (!contextDir.isDirectory())
                continue;
            StandardContext context = new StandardContext();
            context.setName(contextDir.getName());
            context.addLifecycleListener(new ContextConfig());
            host.addChild(context);
        }
    }
}
